package com.example.imtoken.modules.main.wallet.details.trade.details

import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.LogUtils
import com.example.imtoken.core.base.BaseViewModel
import com.example.imtoken.core.http.BaseObserver
import com.example.imtoken.core.logic.network.RetrofitUtils
import com.example.imtoken.entitys.http.ResponseEntity
import com.example.imtoken.entitys.http.TransactionInfoEntity
import com.example.imtoken.room.base.AppDataBase
import com.example.imtoken.room.schema.TransactionRecordSchema
import io.reactivex.schedulers.Schedulers

class TransferDetailsViewModel : BaseViewModel() {

    private val transactionRecordSchema = MutableLiveData<TransactionRecordSchema>()

    fun getTransactionRecordSchema(): MutableLiveData<TransactionRecordSchema> {
        return transactionRecordSchema
    }

    fun getData(id: Int) {
        val data = AppDataBase.instance.getTransactionRecordDao().findByIdData(id)
        transactionRecordSchema.value = data

        if (data?.state == 0) transactionInfo()
    }

    private fun transactionInfo() {
        val coin = transactionRecordSchema.value?.coin
        val txid = transactionRecordSchema.value?.txid
        if (coin == null || txid == null) return
        RetrofitUtils.apiService?.transactionInfo(
            coin,
            txid
        )
            ?.subscribeOn(Schedulers.io())
            ?.unsubscribeOn(Schedulers.io())
            ?.subscribe(object : BaseObserver<ResponseEntity<TransactionInfoEntity>>() {
                override fun onSuccess(value: ResponseEntity<TransactionInfoEntity>) {
                    if (value.code == 0) {
                        if (value.data?.size != null) {
                            val data = transactionRecordSchema.value
                            if (data != null) {
                                if (data.state != value.data[0].status) {
                                    data.state = value.data[0].status
                                    if (value.data[0].status == 2) {
                                        //失败,需要更改数据库的失败类型
                                        data.type = 3
                                    }
                                    if (AppDataBase.instance.getTransactionRecordDao()
                                            .updateData(data) > 0
                                    ) {
                                        LogUtils.e("更新详情状态成功")
                                    } else {
                                        LogUtils.e("更新详情状态失败")
                                    }
                                    transactionRecordSchema.postValue(data)
                                }
                            }
                        }
                    } else {
                        LogUtils.e(value.msg)
                    }
                }

                override fun onFailed(e: Throwable) {

                }

            })
    }

}